import {
	env
} from './env.js'

const LOG_SUCCESS = '\x1B[32m%s\x1B[0m'
const LOG_FAIL = '\x1B[31m%s\x1B[0m'

const request = (params) => {

	const needLoading = params.hasOwnProperty('needLoading') ? params.needLoading : true

	let loading = true
	if (needLoading && loading) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
	}

	// 除了登录接口外，都需要token
	const token = params.url !== '/app/user/login' ? uni.getStorageSync('userInfo').token : ''

	return new Promise((resolve, reject) => {
		uni.request({
			url: env.baseUrl + (params.url || ''),
			method: params.method || 'POST',
			timeout: 60000,
			sslVerify: true, // 本地真机调试要改成false
			header: {
				'content-type': (params.header && params.header['content-type']) ||
					'application/json',
				...params.header,
				utoken: token
			},
			data: params.data || {},

			success: (res) => {
				console.log(LOG_SUCCESS, `${params.url}`, res.data, res)
				if (res.code === 3) {
					uni.removeStorageSync('userInfo')
					uni.reLaunch({
						url: '/pages/loginPage/index'
					})
					return
				}
				resolve(res.data)
			},
			fail: (err) => {
				console.log(LOG_FAIL, `${params.url}`, err)
				reject(err)
			},
			complete: () => {
				if (needLoading && loading) {
					uni.hideLoading()
				}
				loading = false
			}
		})
	})
}

export default request